#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int low, high;
    TreeNode* trimBST(TreeNode* root, int _low, int _high) {
        low = _low;
        high = _high;


        return dfs(root);
    }

    TreeNode* dfs(TreeNode* node)
    {
        if (node == nullptr)
            return nullptr;

        if (node->val > high)
        {
            return dfs(node->left);
        }
        else if (node->val < low)
        {
            return dfs(node->right);
        }

        node->left = dfs(node->left);
        node->right = dfs(node->right);

        return node;
    }
};